/**
 * Copyright (c)2014 快诺迅汇(长沙)网络技术股份有限公司。
 * 版权所有
 */
package com.lehe.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lehe.common.Contants;
import com.lehe.common.utils.StringUtil;
import com.lehe.entry.wx.message.RespBaseMessage;
import com.lehe.entry.wx.message.RespUserOpenIdMessage;
import com.lehe.service.IMessageConvert;
import com.lehe.service.ISendRedpackService;
import com.lehe.service.IWeChatExecuteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 类的功能描述<br>
 *
 * @author 王丹
 * @FileName WeiXinController.java<br>
 * @Language Java<br>
 * @date 2016-07-22<br>
 */
@Controller
@RequestMapping("/ec2wx")
public class Ec2WeixinController extends Basecontroller {

	@SuppressWarnings("rawtypes")
	@Autowired
    @Qualifier("queryUserOpenIdExecuteService")
    private IWeChatExecuteService queryUserOpenIdExecuteService;

    @Autowired
    private ISendRedpackService sendRedpackService;
	
    @Autowired
    protected IMessageConvert messageConvert;

    private static Map<String, Map<String, String>> userOpenIdMap = new HashMap<>();

    @RequestMapping(value = "/openid/{code}", method = RequestMethod.GET)
    @ResponseBody
    public String openid(@PathVariable String code) throws IOException {
    	logger.info("收到ec请求，获取ipenid，code="+code);
        synchronized (userOpenIdMap){
            long reqTimeMillis = System.currentTimeMillis();
            if(userOpenIdMap.containsKey(code) && Long.parseLong(userOpenIdMap.get(code).get("expiresin")) > reqTimeMillis){
                String openId = userOpenIdMap.get(code).get("openid");
                logger.info("返回openid，open=" + openId);
                return openId;
            }else{
                Map<String, String> map = new HashMap<String, String>();
                map.put("appid", Contants.APP_ID);
                map.put("secret", Contants.APP_SECRET);
                map.put("grant_type", Contants.GRANT_TYPE_QUERY_OPENID);
                map.put("code", code);
                try {
                    RespBaseMessage respMessage = queryUserOpenIdExecuteService.execute(map);
                    RespUserOpenIdMessage respUserOpenIdMessage = (RespUserOpenIdMessage) respMessage;
                    Map<String, String> userMap = new HashMap<>();
                    userMap.put("openid", respUserOpenIdMessage.getOpenid());
                    long curTimeMillis = System.currentTimeMillis();
                    String exp = String.valueOf(5 * 60 * 1000 + curTimeMillis);
                    userMap.put("expiresin", exp);
                    userOpenIdMap.put(code, userMap);
                    logger.info("获取openid，open="+respUserOpenIdMessage.getOpenid());
                    return respUserOpenIdMessage.getOpenid();
                } catch (Exception e) {
                    logger.error("获取openId失败:", e);
                }
                return "";
            }
        }
    }

    @RequestMapping(value = "/send/hb")
    @ResponseBody
    public boolean sendRedpack(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	logger.warn("收到ec发送红包请求");
    	boolean ret = false;
        logger.info("客户端发起了微信发送红包申请");
        try {
            String orderNo = request.getParameter("orderNo");
            String reOpenid = request.getParameter("reOpenid");
            String totalAmt = request.getParameter("totalAmt");
            String totalNum = request.getParameter("totalNum");
            String wishing = request.getParameter("wishing");
            String actName = request.getParameter("actName");
            String remark = request.getParameter("remark");
            String remoteIp = StringUtil.getIpAddr(request);
            logger.info("远程客户端地址：" + remoteIp + String.format("，请求参数：orderNo=%s,reOpenid=%s,totalAmt=%s,totalNum=%s,wishing=%s,actName=%s,remark=%s",
                    orderNo, reOpenid, totalAmt, totalNum, wishing, actName, remark));
            if(StringUtil.isBlank(orderNo) || StringUtil.isBlank(reOpenid) || StringUtil.isBlank(totalAmt) || StringUtil.isBlank(totalNum)
                    || StringUtil.isBlank(wishing) || StringUtil.isBlank(actName) || StringUtil.isBlank(remark)){
                logger.warn("请求参数不能为空");
                return false;
            }
            if(Double.valueOf(totalAmt) > 200 || Double.valueOf(totalAmt) < 1){
                logger.warn("红包金额介于【1.00元-200.00元】之间");
                return false;
            }
            if(StringUtil.filterIp(remoteIp)){
                logger.warn("远程客户端地址不在调用者白名单");
                return false;
            }
            if(StringUtil.filterTestIp(remoteIp)){
                logger.warn("远程客户端地址为测试IP，直接返回true");
                return true;
            }else {
                Double d = Double.parseDouble(totalAmt) * 100;
                ret = sendRedpackService.sendRedpack(orderNo, reOpenid, d.intValue(), Integer.parseInt(totalNum), wishing, actName, remark);
            }
        } catch (Exception e) {
            logger.error("发送红包失败:", e);
        }
        logger.info("微信发送红包结束，结果为" + ret);
        return ret;
    }
}
